package com.ygqh.baby.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ygqh.baby.ao.OffShop;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.kids.entity.bo.KidsOrder;
import com.ygqh.baby.kids.handler.KidsHttpClient;
import com.ygqh.baby.kids.service.KidsOrderService;
import com.ygqh.baby.po.BiSupplierOrderDay;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author: sunshuo
 * @Date: 2019/6/17/017 11:21
 * @Version: 1.0
 */
@Component
public class OffShopBiOrderHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private KidsHttpClient kidsHttpClient;
    @Autowired
    private KidsOrderService kidsOrderService;

    @Value("${kids.order.pull.url}")
    private String kidsOrderPullUrl;
    @Value("${off.order.pull.url}")
    private String offOrderPullUrl;

    public void statisticsOrderByTime(Date startTime, Date endTime) {
        statisticsOrderByTime(startTime, endTime, OffShop.Kids, OffShop.TaiYangGong);
    }

    public List<BiSupplierOrderDay> statisticsSupplierOrderByDate(Date startDate, Date endDate) {
        return statisticsSupplierOrderByDate(startDate, endDate, OffShop.Kids, OffShop.TaiYangGong);
    }


    public void statisticsOrderByTime(Date startTime, Date endTime, OffShop... offShops) {
        if (offShops == null || offShops.length == 0) {
            return;
        }
        for (OffShop offShop : offShops) {
            try {
                List<KidsOrder> orderList = getOrderDetailListFromOffShop(startTime, endTime, offShop);
                if (CollectionUtils.isEmpty(orderList)) {
                    logger.info("【OffShopBiOrderHandler statisticsOrderByTime】：" +
                                    "{} -> {} 未拉取到线下店【" + offShop + "】订单数据",
                            DateConvertUtils.formatDateTime(startTime), DateConvertUtils.formatDateTime(endTime));
                    continue;
                }
                kidsOrderService.buildBiOrderDayFromKids(orderList, DateConvertUtils.getDateStart(startTime), offShop);
            } catch (Exception e) {
                logger.error("【OffShopBiOrderHandler statisticsOrderByTime】：统计线下店【" + offShop + "】订单数据异常", e);
                throw new RuntimeException(e);
            }
        }
    }

    public void resetBiOrder(Date startTime, Date endTime, OffShop offShop) {
        try {
            List<KidsOrder> orderList = getOrderDetailListFromOffShop(startTime, endTime, offShop);
            kidsOrderService.resetBiOrder(orderList, offShop);
        } catch (YgHttpException e) {
            e.printStackTrace();
            logger.error("【OffShopBiOrderHandler statisticsOrderByTime】：统计线下店【" + offShop + "】订单数据异常,startTime={},endTime={}", startTime, endTime, e);
        }
    }

    public List<BiSupplierOrderDay> statisticsSupplierOrderByDate(Date startDate, Date endDate, OffShop... offShops) {
        List<BiSupplierOrderDay> orderBoList = new ArrayList<>();
        if (offShops == null || offShops.length == 0) {
            return orderBoList;
        }
        for (OffShop offShop : offShops) {
            try {
                List<KidsOrder> orderList = getOrderDetailListFromOffShop(startDate, endDate, offShop);
                if (CollectionUtils.isEmpty(orderList)) {
                    logger.info("【OffShopBiOrderHandler statisticsSupplierOrderByDate】：" +
                                    "{} -> {} 未拉取到线下店【" + offShop + "】订单数据",
                            DateConvertUtils.format(startDate), DateConvertUtils.format(endDate));
                    continue;
                }
                orderBoList.addAll(kidsOrderService.buildBiSupplierOrderDayFromKids(orderList, startDate, offShop));
            } catch (Exception e) {
                logger.error("【OffShopBiOrderHandler statisticsSupplierOrderByDate】：统计线下店【" + offShop + "】订单数据异常", e);
            }
        }
        return orderBoList;
    }

    private List<KidsOrder> getOrderDetailListFromOffShop(Date startTime, Date endTime, OffShop offShop) throws YgHttpException {
        String url = getOrderListUrl(offShop);
        Map<String, String> params = new HashMap<>(2);
        params.put("startTime", DateConvertUtils.formatDateTime(startTime));
        params.put("endTime", DateConvertUtils.formatDateTime(endTime));
        params.put("platformNo", offShop.getPlatformNo());
        JSONObject asJson = kidsHttpClient.get(url, params);
        JSONArray data = asJson.getJSONArray("data");
        if (data == null) {
            return null;
        }
        return JSON.parseArray(JSON.toJSONString(data), KidsOrder.class);
    }

    private String getOrderListUrl(OffShop offShop) {
        if (OffShop.Kids.equals(offShop)) {
            return kidsOrderPullUrl;
        } else if (OffShop.TaiYangGong.equals(offShop)) {
            return offOrderPullUrl;
        }
        throw new RuntimeException("未知的线下店铺");
    }
}
